<?php

/**
 * @Author: chenjianghui
 * @Date:   2018-08-07 11:22:13
 * @Last Modified by:   chenjianghui
 * @Last Modified time: 2018-08-10 10:07:31
 */
namespace app\common\model;

use app\common\lib\Encryption;
use think\Db;
use think\Model;
use think\Request;

class UserBackUps extends Model
{
    protected $name = 'user';

    /**
     * 手机短信注册
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:55:27+0800
     * @return   [type]                   [description]
     */
    public function smsRegister()
    {
        $this->setSalt();
        $this->password   = $this->encryPassword(md5($this->password));
        $this->reg_time   = time();
        $this->reg_ip     = request()->ip();
        

        Db::startTrans();
        try {

            $user   = $this->where("mobile", $this->mobile)->find(); //验证该电话号码是否注册
            $result = 0;
            if ($user) {
                $id         = $user['uid'];
            } else {
                $result = $this->allowField(true)->save();
                $id     = $this->uid;
            }
            if ($result) {
                Db::commit();
                return $id;
            } else {
                Db::rollback();
            }
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 生成用户唯一登录安全码
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:55:42+0800
     * @param    integer                  $length 长度
     */
    public function setSalt($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
        $key   = '';
        for ($i = 0; $i < $length; $i++) {
            $key .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        $this->sec_code = $key;
        return $key;
    }

    /**
     * 密码加密
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:56:11+0800
     * @param    string                   $password 密码
     * @return   [type]                             [description]
     */
    public function encryPassword($password)
    {
        $password = preg_match('/^\w{32}$/', $password) ? $password : md5(stripslashes($password));

        return md5($password . md5($this->sec_code));
    }

    /**
     * 登录（普通登录）
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:56:33+0800
     * @param    [type]                   $data [description]
     * @return   [type]                         [description]
     */
    public function login($data)
    {
        $data['password'] = Encryption::decode($data['password']);

        if ($this->verifyPassword($data['password'])) {
            $access_token          = \app\common\lib\User::encode_token($this->toArray());
            $this->access_token    = $access_token;
            $this->last_login_time = time();
            $this->last_login_ip   = request()->ip();
            if ($this->save()) {
                return $access_token;
            }
        }
        return false;
    }


    /*
     * 用户快速登陆
     * */
    public function loginFast()
    {
        $token                = \app\common\lib\User::encode_token($this->toArray());
        $data['access_token'] = $token;
        if ($this->save($data)) {
            return $token;
        }
        return false;
    }


    /**
     * 密码验证
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:57:06+0800
     * @param    [type]                   $password 密码
     * @return   [type]                             [description]
     */
    public function verifyPassword($password)
    {
        if ($this->password == $this->encryPassword($password)) {
            return true;
        }
        return false;
    }

    /**
     * 手机快速登录
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:57:26+0800
     * @return   [type]                   [description]
     */
    public function loginByMobile()
    {
        $access_token          = \app\common\lib\User::encode_token($this->toArray());
        $this->access_token    = $access_token;
        $this->last_login_time = time();
        $this->last_login_ip   = request()->ip();
        if ($this->save()) {
            return $access_token;
        } else {
            return false;
        }
    }

    /**
     * 密码修改
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:57:47+0800
     * @param    [type]                   $password 密码
     * @return   [type]                             [description]
     */
    public function changePassword($password)
    {
        if ($this->password == $this->encryPassword(md5($password))) {
            renderJson('两次密码不能一样', 0);
        } else {
            $this->password = $this->encryPassword(md5($password));
            return $this->save();
        }

    }

    /**
     * 更新用户个人信息
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:59:52+0800
     * @param    array                   $data  需要更新的用户资料
     * @return   int                            用户id
     */
    public function updateUserInfo($data)
    {
        if (!is_array($data)) {
            renderJson('传递参数不合法', 0);
        }
        $this->allowField(true)->save($data);

        return $this->uid;
    }

    /**
     * 用户名获取
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:58:50+0800
     * @param    [type]                   $uid 用户id
     * @return   string                        用户名
     */
    public function getNameById($uid)
    {
        $user_info = $this->where('uid', $uid)->field('username')->find();
        $username  = $user_info['username'] ?: '';
        return $username;
    }

    /**
     * 获取用户信息
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:58:22+0800
     * @param    int                   $uid   用户id
     * @return   array                        用户信息
     */
    public function getUserInfoById($uid)
    {
        $user_info = $this->where('uid', $uid)->find();
        return $user_info;
    }

    public function getAvatarById($uid)
    {
        $avatar = $this->where('uid',$uid)->value('avatar');
        if ($avatar && !preg_match('/(http:\/\/)|(https:\/\/)/i', $avatar)) {
            $avatar = 'http://' . $_SERVER['HTTP_HOST'] . $avatar;
        } else if ($avatar && preg_match('/(http:\/\/)|(https:\/\/)/i', $avatar)) {
            $avatar = $avatar;
        } else {
            $avatar = 'http://' . $_SERVER['HTTP_HOST'] . '/static/images/head_img.png';
        }
        return $avatar;
    }

    /**
     * 退出
     * @Author   chenjianghui
     * @DateTime 2018-08-07T16:34:33+0800
     * @return   [type]                   [description]
     */
    public function logout()
    {
        $this->access_token = '';
        return $this->save();
    }

}
